package com.clei.utils;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;

/**
 * 下载工具类
 *
 * @author KIyA
 */
public final class DownloadUtil {

    /**
     * 将远程文件下载到本地
     *
     * @param fileUrl 文件httpUrl
     * @param toFile  输出文件
     */
    public static void downloadToLocal(String fileUrl, String toFile) {

        try (FileOutputStream fos = new FileOutputStream(toFile)) {
            download(fileUrl, fos);
        } catch (Exception e) {
            PrintUtil.log("downloadToLocal error fileUrl : {}, toFile : {}", fileUrl, toFile, e);
        }
    }

    /**
     * java指定文件url下载
     *
     * @param fileUrl      文件httpUrl
     * @param outputStream 输出流
     */
    public static void download(String fileUrl, OutputStream outputStream) {
        InputStream inputStream = null;
        try {
            URL url = new URL(fileUrl);
            inputStream = url.openStream();
        } catch (Exception e) {
            PrintUtil.log("download error fileUrl : {}", fileUrl, e);
        }
        if (null != inputStream) {
            StreamUtil.transfer(inputStream, outputStream);
        }
    }
}
